import { createServer } from 'http';
import app from './app';
import { initializeDatabase } from './config/database';
import { logger } from './utils/logger';
import { initializeModels } from './models';

const PORT = Number(process.env.PORT) || 3000;
const HOST = process.env.HOST || '0.0.0.0';

// 启动服务器
async function startServer(): Promise<void> {
  try {
    // 初始化数据库连接
    await initializeDatabase();
    logger.info('Database initialized successfully');
    
    // 初始化模型
    await initializeModels();
    logger.info('Models initialized successfully');
    
    // 创建HTTP服务器
    const server = createServer(app.callback());

    // 启动服务器
    server.listen(PORT, HOST, () => {
      logger.info(`Server running on http://${HOST}:${PORT}`);
      logger.info(`Environment: ${process.env.NODE_ENV || 'development'}`);
    });

    // 设置服务器超时
    server.timeout = 30000; // 30秒
    
    // 优雅关闭处理
    const gracefulShutdown = (signal: string) => {
      logger.info(`Received ${signal}, shutting down gracefully...`);
      
      server.close(async () => {
        logger.info('HTTP server closed');
        
        try {
          // 关闭数据库连接
          const { closeDatabase } = require('./config/database');
          await closeDatabase();
          logger.info('Database connections closed');
          
          logger.info('Graceful shutdown completed');
          process.exit(0);
        } catch (error) {
          logger.error('Error during graceful shutdown:', error);
          process.exit(1);
        }
      });
      
      // 强制关闭超时
      setTimeout(() => {
        logger.error('Could not close connections in time, forcefully shutting down');
        process.exit(1);
      }, 10000); // 10秒后强制关闭
    };
    
    // 监听关闭信号
    process.on('SIGTERM', () => gracefulShutdown('SIGTERM')); // 收到终止信号
    process.on('SIGINT', () => gracefulShutdown('SIGINT')); // 收到 Ctrl+C 信号
    
    // 处理未捕获的异常
    process.on('uncaughtException', (error) => {
      logger.error('Uncaught Exception:', error);
      process.exit(1);
    });
    
    // 处理未处理的Promise拒绝
    process.on('unhandledRejection', (reason, promise) => {
      logger.error('Unhandled Rejection:', { promise, reason });
      process.exit(1);
    });
    
  } catch (error) {
    logger.error('Failed to start server:', error);
    process.exit(1);
  }
}

// 启动服务器
startServer();

export { startServer };